<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="100px"
    class="user-form"
  >
    <el-form-item label="用户名称" prop="userName">
      <el-input v-model="form.userName" placeholder="请输入用户名称" />
    </el-form-item>

    <el-form-item label="用户头像">
      <el-upload
        :action="uploadAction"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
        list-type="picture-card"
        :file-list="fileList"
        :limit="1"
        :on-exceed="handleExceed"
        :headers="uploadHeaders"
      >
        <el-icon><Plus /></el-icon>
        <template #tip>
          <div class="el-upload__tip">支持jpg、png格式</div>
        </template>
      </el-upload>
      <el-image
        v-if="form.pic"
        :src="form.pic"
        style="width: 100px; height: 100px; margin-top: 10px"
        fit="cover"
      />
    </el-form-item>

    <el-form-item label="联系电话" prop="phone">
      <el-input v-model="form.phone" placeholder="请输入联系电话" />
    </el-form-item>

    <el-form-item label="电子邮箱" prop="email">
      <el-input v-model="form.email" placeholder="请输入电子邮箱" />
    </el-form-item>

    <el-form-item label="用户状态" prop="status">
      <el-switch
        v-model="form.status"
        active-value="1"
        inactive-value="0"
        active-text="启用"
        inactive-text="禁用"
      />
    </el-form-item>

    <el-form-item label="关联角色" prop="roleId">
      <el-select
        v-model="form.roleId"
        placeholder="请选择用户关联的角色"
        style="width: 100%"
      >
        <el-option
          v-for="role in roleList"
          :key="role.roleId"
          :label="role.roleName"
          :value="Number(role.roleId)"
        />
        <!-- 如果没有匹配项，显示默认选项 -->
        <el-option
          v-if="form.roleId && !roleList.some(r => String(r.roleId) === String(form.roleId))"
          label="未知角色"
          :value="form.roleId"
          disabled
        />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { reactive, ref, watch, computed } from 'vue'
import { addUser, updateUser } from '@/api/permission'
import { assignUserRoles } from '@/api/permission'
import { useUserStore } from '@/stores/user'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({})
  },
  roleList: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['save', 'cancel'])

const formRef = ref(null)
const form = reactive({
  id: '',
  userName: '',
  pic: '',
  phone: '',
  email: '',
  status: '1',
  roleId: undefined
})

const fileList = ref([])

// 上传相关配置
const uploadAction = computed(() => {
  return '/api/order/order-client/api/file/upload'
})

const uploadHeaders = computed(() => {
  const userStore = useUserStore()
  const token = userStore.userInfo?.userInfoVO?.token
  return token ? { Authorization: `Bearer ${token}` } : {}
})

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      form.id = val.id || ''
      form.userName = val.userName || ''
      form.pic = val.pic || ''
      form.phone = val.phone || ''
      form.email = val.email || ''
      form.status = val.status !== undefined ? String(val.status) : '1'

      // 处理角色ID，确保类型一致性
      if (val.roleIds && Array.isArray(val.roleIds) && val.roleIds.length > 0) {
        const roleId = val.roleIds[0]
        // 检查角色是否在角色列表中
        const roleExists = props.roleList.some(role => String(role.roleId) === String(roleId))
        if (roleExists) {
          form.roleId = Number(roleId)
        } else {
          form.roleId = undefined
        }
      } else {
        form.roleId = undefined
      }

      // 处理头像
      if (val.pic) {
        fileList.value = [{ url: val.pic, name: '用户头像' }]
      } else {
        fileList.value = []
      }
    }
  },
  { immediate: true }
)

const rules = {
  userName: [
    { required: true, message: '请输入用户名称', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名称长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的电子邮箱格式', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择关联角色', trigger: 'change' }
  ]
}

// 文件上传前检查
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  return true
}

// 处理上传成功
const handleUploadSuccess = (response, uploadFile) => {
  console.log('上传响应:', response)
  if (response && response.code === 0 && response.data) {
    // 处理返回的数据，确保正确获取图片URL
    if (typeof response.data === 'string') {
      // 直接返回URL字符串
      form.pic = response.data
      fileList.value = [{
        name: uploadFile.name,
        url: response.data
      }]
    } else if (response.data.url) {
      // 返回包含url字段的对象
      form.pic = response.data.url
      fileList.value = [{
        name: response.data.name || uploadFile.name,
        url: response.data.url
      }]
    } else if (response.data.path) {
      // 处理可能返回path字段的情况
      form.pic = response.data.path
      fileList.value = [{
        name: response.data.name || uploadFile.name,
        url: response.data.path
      }]
    }
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败: ' + (response?.msg || '未知错误'))
  }
}

// 处理上传失败
const handleUploadError = (error) => {
  console.error('图片上传失败', error)
  ElMessage.error('图片上传失败: ' + (error.message || '未知错误'))
}

// 文件超出限制
const handleExceed = () => {
  ElMessage.warning('只能上传一张图片')
}

// 移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  form.pic = ''
  fileList.value = []
}

const handleCancel = () => {
  emit('cancel')
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    // 准备用户基本信息
    const userData = {
      userName: form.userName,
      pic: form.pic || '',  // 确保传递图片路径，如果没有则传递空字符串
      phone: form.phone,
      email: form.email,
      status: Number(form.status)
    }

    let userId
    let userResponse

    // 保存用户基本信息
    if (form.id) {
      userResponse = await updateUser(form.id, userData)
      userId = form.id
      ElMessage.success('用户信息更新成功')
    } else {
      // 新增用户
      userResponse = await addUser(userData)
      userId = userResponse.data?.id || userResponse.id
      ElMessage.success('用户创建成功')
    }

    // 更新用户角色
    if (form.roleId !== undefined && userId) {
      try {
        const roleId = Number(form.roleId)
        // 调用角色分配API
        await assignUserRoles(userId, roleId)
        ElMessage.success('用户角色分配成功')
      } catch (roleError) {
        console.error('Role assignment error:', roleError)
        // 根据错误响应调整错误信息显示
        const errorMsg = roleError.msg || roleError.message || '用户角色分配失败'
        ElMessage.error('用户角色分配失败: ' + errorMsg)
      }
    }

    emit('save')
  } catch (error) {
    if (error.errors) {
      const errorMsg = Object.values(error.errors).flat().join('；')
      ElMessage.error(errorMsg || '表单验证失败，请检查输入')
    } else if (error.msg) {
      ElMessage.error('保存失败: ' + error.msg)
    } else {
      ElMessage.error('保存失败: ' + (error.message || '未知错误'))
      console.error('Save error:', error)
    }
  }
}
</script>

<style scoped>
.user-form {
  margin-top: 20px;
}

::v-deep .el-form-item {
  margin-bottom: 15px;
}
</style>
